package com.asset.salesforce.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;

import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.asset.salesforce.converter.AccountConverter;
import com.asset.salesforce.domain.Account;
import com.asset.salesforce.domain.City;
import com.asset.salesforce.domain.Country;
import com.asset.salesforce.domain.DeletedAccount;
import com.asset.salesforce.domain.Employee;
import com.asset.salesforce.domain.Role;
import com.asset.salesforce.domain.UpdateChatter;
import com.asset.salesforce.enums.FOLLOWTYPE;
import com.asset.salesforce.enums.INDUSTRY;
import com.asset.salesforce.enums.TYPE;
import com.asset.salesforce.enums.UPDATETYPE;
import com.asset.salesforce.form.AccountData;
import com.asset.salesforce.form.AccountForm;
import com.asset.salesforce.form.DataTable;
import com.asset.salesforce.service.AccountService;
import com.asset.salesforce.service.CalendarService;
import com.asset.salesforce.service.CheckingUtilsService;
import com.asset.salesforce.service.CityService;
import com.asset.salesforce.service.CountryService;
import com.asset.salesforce.service.DeletedAccountService;
import com.asset.salesforce.service.JoinRequestService;
import com.asset.salesforce.service.LeadService;
import com.asset.salesforce.service.PostService;
import com.asset.salesforce.service.UpdateChatterService;
import com.asset.salesforce.service.UserShiroService;


@Controller
public class AccountController {
	@Autowired
	private AccountService accountService;
	
	@Autowired
	private LeadService leadService;

	@Autowired 
	private CountryService countryService;
	
	@Autowired
	private CityService cityService;
	@Autowired
	private UpdateChatterService updateChatterService;

	@Autowired
	private PostService postService;
	
	@Autowired
	private DeletedAccountService deletedAccountService;
	
	@Autowired
	private CheckingUtilsService checkingUtilsService;
	
	@Autowired
	private JoinRequestService joinRequestService;
	
	@Autowired
	private CalendarService calendarService;
	
	@Autowired
	private UserShiroService userShiroService;
	
	@RequestMapping(value="/getAllAccounts", method = RequestMethod.GET,produces="application/json;charset=UTF-8")
	@ResponseBody
	public DataTable<AccountData> getAllAccounts(HttpSession session){
		DataTable<AccountData> dataTable = new DataTable<AccountData>();
		Employee userDetails = (Employee) session.getAttribute("userDetails");
		List<Account>accounts = new ArrayList<Account>();
		if (userDetails.getIsOwner()==true){
			accounts = accountService.getAllAccountByCompany(userDetails.getCompany().getId());
		}
		else{
			accounts = accountService.getAllAccountByEmpId(userDetails.getId());
		}
		List<AccountData>accountData = new ArrayList<AccountData>();
		for (Account account : accounts) {
			AccountData data = new AccountData();
			data.setId(account.getId());
			data.setAccountName(account.getAccountName());
			data.setCompanyName(account.getCompanyName());
			data.setAccountOwner(userDetails.getfName()+" "+userDetails.getlName());
			account.setIsFollowed(checkingUtilsService.checkIfCurrentFollowThatAccount(userDetails, account));
			if(account.getIsFollowed()==true){
				data.setIsFollowed(account.getId().toString()+"/"+"true");
			}
			else{
				data.setIsFollowed(account.getId().toString()+"/"+"false");
			}
			accountData.add(data);
		}
		dataTable.setAaData(accountData);
		return dataTable;
	}
	
	@RequestMapping(value="/accounts", method=RequestMethod.GET)
	public String getAccount(Model model,HttpSession session) {
		if(null ==session.getAttribute("userDetails") ){
				return "redirect:/s/login.html";
			}
		//Employee userDetails = (Employee)session.getAttribute("userDetails");
		List<Role>userRoles = userShiroService.getCurrentUser().getRoles();
		List<String>roles = new ArrayList<String>();
		for (Role role : userRoles) {
			roles.add(role.getName());
		}
		model.addAttribute("userRoles", roles);
		joinRequestService.getJoinRquestNo(session, model);
		calendarService.getAppointmentEventsNo(session, model);
		calendarService.getCallEventssNo(session, model);
		return "accounts";
	}

	@RequestMapping(value="/new-account",method=RequestMethod.GET)
	public String addNewAccount(Model model,HttpSession session, ModelMap modelMap){
		if (SecurityUtils.getSubject().hasRole("accountAdd")){
		if(null ==session.getAttribute("userDetails") ){
			return "redirect:/s/login.html";
		}
		Employee userDetails = (Employee)session.getAttribute("userDetails");
		model.addAttribute("userDetails",userDetails);
		TYPE[] types =TYPE.values();
		INDUSTRY[] industries = INDUSTRY.values();
		AccountForm accountForm = new AccountForm();
		modelMap.addAttribute("accountForm", accountForm);
		model.addAttribute("industries", industries);
		model.addAttribute("types", types);
		List<Country> countries = new ArrayList<Country>();
		countries =  countryService.getAll();
		model.addAttribute("countries", countries);
		joinRequestService.getJoinRquestNo(session, model);
		calendarService.getAppointmentEventsNo(session, model);
		calendarService.getCallEventssNo(session, model);
		return "new-account";
		}
		else{
			return "accessDenied";
		}
	}
	
	@RequestMapping(value="/new-account",method=RequestMethod.POST)
	public String postNewAccount(Model model,HttpSession session,
								@Valid @ModelAttribute("accountForm") AccountForm accountForm,BindingResult result){
		Employee userDetails = (Employee)session.getAttribute("userDetails");

		List<Account> accounts = accountService.getAllAccountByEmpId(userDetails.getId());
		if(accounts.size()>0){
			for (Account account : accounts) {
				if(accountForm.getPhone()!=null&&!accountForm.getPhone().equalsIgnoreCase("")){
					if(account.getPhone()!=null&&!account.getPhone().equalsIgnoreCase("")){
						if(account.getPhone().equalsIgnoreCase(accountForm.getPhone())){
							result.rejectValue("phone", "phone","this phone already exists");
						}
					}
				}
				if(accountForm.getCompanyName()!=null&&!accountForm.getCompanyName().equalsIgnoreCase("")){
					if(account.getCompanyName()!=null&&!account.getCompanyName().equalsIgnoreCase("")){
						if(account.getCompanyName().equalsIgnoreCase(accountForm.getCompanyName())){
							result.rejectValue("companyName", "companyName","this company already exists");
						}
					}
				}
				if(accountForm.getMobile()!=null&&!accountForm.getMobile().equalsIgnoreCase("")){
					if(account.getMobile()!=null&&!account.getMobile().equalsIgnoreCase("")){
						if(account.getMobile().equalsIgnoreCase(accountForm.getMobile())){
							result.rejectValue("mobile", "mobile","this mobile already exists");
						}
					}
				}
			}
		}
		if(result.hasErrors()){
			System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>....."+result.getAllErrors().size());
			model.addAttribute("accountForm", accountForm);
			TYPE[] types =TYPE.values();
			INDUSTRY[] industries = INDUSTRY.values();
			
			
			model.addAttribute("accountForm", accountForm);
			model.addAttribute("industries", industries);
			model.addAttribute("types", types);
			List<Country> countries = new ArrayList<Country>();
			countries =  countryService.getAll();
			model.addAttribute("countries", countries);
			List<City> cities = new ArrayList<City>();
			cities = cityService.getAllCityByCountryId(accountForm.getCountry());
			model.addAttribute("cities",cities);
			joinRequestService.getJoinRquestNo(session, model);
			calendarService.getAppointmentEventsNo(session, model);
			calendarService.getCallEventssNo(session, model);
			return "new-account";
		}
		/*contact.setDate(new Date());
		if(contactForm.getEmail() != null && !contactForm.getEmail().equalsIgnoreCase("")){
			contact.setEmail(contactForm.getEmail());
		}*/
		
		//Industry industry2 = industeryService.getIndusteryById(industry);
		//Type type = typeService.getTypeById(accountType);
		//Country country2 = countryService.getCountryById(country);
		Account account = new Account();
		account.setAccountCreator(userDetails);
		if(accountForm.getAccountName() != null && !accountForm.getAccountName().equalsIgnoreCase("")){
			account.setAccountName(accountForm.getAccountName());
		}
		if(accountForm.getCompanyName() != null && !accountForm.getCompanyName().equalsIgnoreCase("")){
			account.setCompanyName(accountForm.getCompanyName());
		}
		if(accountForm.getAnnualRevenue() != null){
			account.setAnnualRevenue(accountForm.getAnnualRevenue());
		}
		Integer cityId=accountForm.getCity();
		if(accountForm.getCity()!=null && !cityId.equals(0)){
			account.setCity(cityService.getCityById(accountForm.getCity()));
		}
		if(accountForm.getCountry() != null){
			account.setCountry(countryService.getCountryById((accountForm.getCountry())));
		}
		if(accountForm.getDescription() != null && !accountForm.getDescription().equalsIgnoreCase("")){
			account.setDescription(accountForm.getDescription());
		}
		if(accountForm.getEmail() != null && !accountForm.getEmail().equalsIgnoreCase("")){
			account.setEmail(accountForm.getEmail());
		}
		if(accountForm.getEmpNum() != null){
			account.setEmpNum(accountForm.getEmpNum());
		}
		if(accountForm.getFax() != null && !accountForm.getFax().equalsIgnoreCase("")){
			account.setFax(accountForm.getFax());
		}
		if(accountForm.getIndustry() != null){
			INDUSTRY[] industries=	INDUSTRY.values();
			account.setIndustry(industries[accountForm.getIndustry()].getName());
		}
//		if(accountForm.getParentAccount() != null && !accountForm.getParentAccount().equalsIgnoreCase("")){
//			account.setParentAccountId((accountService.getAccountByName(accountForm.getParentAccount())).getId());
//		}
		if(accountForm.getPhone() != null && !accountForm.getPhone().equalsIgnoreCase("")){
			account.setPhone(accountForm.getPhone());
		}
		if(accountForm.getMobile() != null && !accountForm.getMobile().equalsIgnoreCase("")){
			account.setMobile(accountForm.getMobile());
		}
		if(accountForm.getState() != null && !accountForm.getState().equalsIgnoreCase("")){
			account.setState(accountForm.getState());
		}
		if(accountForm.getStreet() != null && !accountForm.getStreet().equalsIgnoreCase("")){
			account.setStreet(accountForm.getStreet());
		}
		if(accountForm.getType() != null){
			TYPE[] types =TYPE.values();
			account.setType(types[accountForm.getType()].getName());
		}
		if(accountForm.getWebsite() != null && !accountForm.getWebsite().equalsIgnoreCase("")){
			account.setWebSite(accountForm.getWebsite());
		}
		if(accountForm.getZipCode() != null && !accountForm.getZipCode().equalsIgnoreCase("")){
			account.setZipCode(accountForm.getZipCode());
		}
		account.setIsDeleted(false);
		Date date = new Date();
		account.setDateCreated(date);
		account.setDateModified(date);
		accountService.addAccount(account);
				model.addAttribute("userDetails",userDetails);
				joinRequestService.getJoinRquestNo(session, model);
				calendarService.getAppointmentEventsNo(session, model);
				calendarService.getCallEventssNo(session, model);
		return "redirect:/s/accounts.html";
	}	
	
	@RequestMapping(value="/edit-account",method=RequestMethod.GET)
	public String getEditLead(Model model,HttpSession session,HttpServletRequest request){
		if (SecurityUtils.getSubject().hasRole("accountEdit")){
		Employee userDetails = (Employee)session.getAttribute("userDetails");
		
		Integer id = Integer.parseInt(request.getParameter("id").toString());	
		Account account = accountService.getAccount(id);
		AccountConverter accountConverter = new AccountConverter();
		AccountForm accountForm = accountConverter.accountConerter(account);		
		model.addAttribute("userDetails",userDetails);
		TYPE[] types = TYPE.values();
		INDUSTRY[] industries = INDUSTRY.values();
		List<Country> countries = new ArrayList<Country>();
		countries =  countryService.getAll();
		if(accountForm.getCountry()!= null){
			List<City> cities = cityService.getAllCityByCountryId(accountForm.getCountry());
			model.addAttribute("cities", cities);
		}
		model.addAttribute("industries", industries);
		model.addAttribute("countries", countries);
		model.addAttribute("accountForm", accountForm);

		model.addAttribute("types", types);
		joinRequestService.getJoinRquestNo(session, model);
		calendarService.getAppointmentEventsNo(session, model);
		calendarService.getCallEventssNo(session, model);
		return"edit-account";
		}
		else{
			return "accessDenied";
		}
	}
	
	@RequestMapping(value="/edit-account",method=RequestMethod.POST)
	public String postEditLead(Model model,HttpSession session,
			@Valid @ModelAttribute("accountForm") AccountForm accountForm,BindingResult result){
		Employee userDetails = (Employee)session.getAttribute("userDetails");
		INDUSTRY[]  industry2 = INDUSTRY.values();
		TYPE[] types2 = TYPE.values();
		List<Account> accounts = accountService.getAllAccountByEmpId(userDetails.getId());
		if(accounts.size()>0){
			for (Account account : accounts) {
				if(accountForm.getPhone()!=null&&!accountForm.getPhone().equalsIgnoreCase("")){
					if(account.getPhone()!=null&&!account.getPhone().equalsIgnoreCase("")){
						if(account.getPhone().equalsIgnoreCase(accountForm.getPhone())){
							result.rejectValue("phone", "phone","this phone already exists");
						}
					}
				}
				if(accountForm.getCompanyName()!=null&&!accountForm.getCompanyName().equalsIgnoreCase("")){
					if(account.getCompanyName()!=null&&!account.getCompanyName().equalsIgnoreCase("")){
						if(account.getCompanyName().equalsIgnoreCase(accountForm.getCompanyName())){
							result.rejectValue("companyName", "companyName","this company already exists");
						}
					}
				}
				if(accountForm.getMobile()!=null&&!accountForm.getMobile().equalsIgnoreCase("")){
					if(account.getMobile()!=null&&!account.getMobile().equalsIgnoreCase("")){
						if(account.getMobile().equalsIgnoreCase(accountForm.getMobile())){
							result.rejectValue("mobile", "mobile","this mobile already exists");
						}
					}
				}
			}
		}

		if(result.hasErrors()){
			System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>....."+result.getAllErrors().size());
			model.addAttribute("accountForm", accountForm);
			
			model.addAttribute("industries", industry2);
			model.addAttribute("types", types2);
			List<Country> countries = new ArrayList<Country>();
			countries =  countryService.getAll();
			model.addAttribute("countries", countries);
			List<City> cities = new ArrayList<City>();
			if(accountForm.getCountry() != null ){
				 cities = cityService.getAllCityByCountryId(accountForm.getCountry());
			 }
			model.addAttribute("cities",cities);
			joinRequestService.getJoinRquestNo(session, model);
			calendarService.getAppointmentEventsNo(session, model);
			calendarService.getCallEventssNo(session, model);
			return "edit-account";
		}
		
		Account account = accountService.getAccount(accountForm.getId());
		account.setAccountCreator(userDetails);

		if(accountForm.getAccountName() != null && !accountForm.getEmail().equalsIgnoreCase("")){
			account.setAccountName(accountForm.getAccountName());
		}
		if(accountForm.getCompanyName() != null && !accountForm.getCompanyName().equalsIgnoreCase("")){
			account.setCompanyName(accountForm.getCompanyName());
		}
		if(accountForm.getAnnualRevenue() != null){
			account.setAnnualRevenue(accountForm.getAnnualRevenue());
		}
		Integer cityId=accountForm.getCity();
		if(accountForm.getCity()!=null && !cityId.equals(0)){
			City city2 = cityService.getCityById(accountForm.getCity());
			account.setCity(city2);
		}
		else{
			account.setCity(null);
		}
		if(accountForm.getCountry() != null){
			account.setCountry(countryService.getCountryById((accountForm.getCountry())));
		}
		if(accountForm.getDescription() != null && !accountForm.getDescription().equalsIgnoreCase("")){
			account.setDescription(accountForm.getDescription());
		}
		if(accountForm.getEmail() != null && !accountForm.getEmail().equalsIgnoreCase("")){
			account.setEmail(accountForm.getEmail());
		}
		if(accountForm.getEmpNum() != null){
			account.setEmpNum(accountForm.getEmpNum());
		}
		if(accountForm.getFax() != null && !accountForm.getFax().equalsIgnoreCase("")){
			account.setFax(accountForm.getFax());
		}
		if(accountForm.getIndustry() != null){
			INDUSTRY[] industries=	INDUSTRY.values();
			account.setIndustry(industries[accountForm.getIndustry()].getName());
		}
		if(accountForm.getPhone() != null && !accountForm.getPhone().equalsIgnoreCase("")){
			account.setPhone(accountForm.getPhone());
		}
		if(accountForm.getMobile() != null && !accountForm.getMobile().equalsIgnoreCase("")){
			account.setMobile(accountForm.getMobile());
		}
		if(accountForm.getState() != null && !accountForm.getState().equalsIgnoreCase("")){
			account.setState(accountForm.getState());
		}
		if(accountForm.getStreet() != null && !accountForm.getStreet().equalsIgnoreCase("")){
			account.setStreet(accountForm.getStreet());
		}
		if(accountForm.getType() != null){
			TYPE[] types =TYPE.values();
			account.setType(types[accountForm.getType()].getName());
		}
		if(accountForm.getWebsite() != null && !accountForm.getWebsite().equalsIgnoreCase("")){
			account.setWebSite(accountForm.getWebsite());
		}
		if(accountForm.getZipCode() != null && !accountForm.getZipCode().equalsIgnoreCase("")){
			account.setZipCode(accountForm.getZipCode());
		}
		account.setIsDeleted(false);
		account.setDateModified(new Date());
		accountService.saveOrUpdate(account);
						model.addAttribute("userDetails",userDetails);
						joinRequestService.getJoinRquestNo(session, model);
						calendarService.getAppointmentEventsNo(session, model);
						calendarService.getCallEventssNo(session, model);
		return"redirect:/s/accounts.html";
	}
	@RequestMapping(value="/delete-account" ,method=RequestMethod.GET)
	public String getDeletePage(HttpServletRequest request,HttpServletResponse response,Model model,HttpSession session) {
		if (SecurityUtils.getSubject().hasRole("accountDelete")){
		Integer id =Integer.parseInt(request.getParameter("id").toString());
		Employee userDetails = (Employee)session.getAttribute("userDetails");
						UpdateChatter updateChatter = new UpdateChatter();
						updateChatter.setAction_emp(userDetails);
						updateChatter.setDate(new Date());
						updateChatter.setFollowedId(id);
						updateChatter.setFollowType(FOLLOWTYPE.Account.getType());
						updateChatter.setUpdateType(UPDATETYPE.Added.getName());
						Account account = accountService.getAccount(id);
						DeletedAccount deletedAccount = new DeletedAccount();
						deletedAccount.setDeletedId(id);
						deletedAccount.setDeleterId(userDetails.getId());
						account.setIsDeleted(true);
						account.setDateModified(new Date());
						accountService.saveOrUpdate(account);
						deletedAccountService.addDeletedAccount(deletedAccount);
						joinRequestService.getJoinRquestNo(session, model);
						calendarService.getAppointmentEventsNo(session, model);
						calendarService.getCallEventssNo(session, model);
		return"redirect:/s/accounts.html";
		}
		else{
			return "accountDelete";
		}
	}
	@RequestMapping(value="/viewAccount",method=RequestMethod.GET)
	public String viewLead(Model model,HttpSession session,HttpServletRequest request) {
		if (SecurityUtils.getSubject().hasRole("accountView")){
		Employee userDetails=(Employee)session.getAttribute("userDetails");
		if(null ==session.getAttribute("userDetails") ){
			return "redirect:/s/login.html";
		}
		 Object object = request.getParameter("b");
		 if(object != null){
			 model.addAttribute("chatter", "chatter");
		 }
		Account account = accountService.getAccount(Integer.parseInt(request.getParameter("id")));
		model.addAttribute("account", account);
		model.addAttribute("userDetails", userDetails);
		calendarService.getAppointmentEventsNo(session, model);
		calendarService.getCallEventssNo(session, model);
		joinRequestService.getJoinRquestNo(session, model);
		return "viewAccount";
		}
		else{
			return "accessDenied";
		}
	}
}
